package org.yejiali.service.impl;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.yejiali.common.enums.AppHttpCodeEnum;
import org.yejiali.common.response.ResponseResult;
import org.yejiali.service.UploadService;
import org.yejiali.util.PathUtils;
import java.io.InputStream;

/**
 * @Author:yejiali
 * @Date:2025/3/3-03-03-15:09
 * @Decsription:org.yejiali.service.impl
 * @Version:1.0
 */
@Data
@Service("uploadService")
@ConfigurationProperties(prefix = "oss")
public class UploadServiceImpl implements UploadService {

    private String accessKey;
    private String secretKey;
    private String bucket;
    @Override
    public ResponseResult upload(MultipartFile img) {

        // TODO 判断文件类型或文件大小
        //获取原始文件名对文件类型进行判断
        String originalFilename=img.getOriginalFilename();
        if(!originalFilename.endsWith(".png")){
            //不是以.jpg结尾，则上传失败
            return ResponseResult.errorResult(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }

        //如果判断通过则上传到oss
        String url=uploadOss(img,PathUtils.generateFilePath(originalFilename));
        return ResponseResult.okResult(url);
    }
    private String uploadOss(MultipartFile imgFile,String filePath){
        //构造一个带指定 Region 对象的配置类 (这里我用的是华北，可以在文档中查看地区配置，但这里建议使用自动配置)
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //指定文件存储时的文件名
        String key = filePath;
        try {
            //前端传来的文件转换成inputStream
            InputStream inputStream = imgFile.getInputStream();
            //创建凭证
            Auth auth = Auth.create(accessKey, secretKey);
            //上传凭证
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "http://sse8tw0rq.hb-bkt.clouddn.com/"+key; //TODO 这里的外链域名最好不要写死，最好是在配置文件中配置
            } catch (QiniuException ex) {
                ex.printStackTrace();
                if (ex.response != null) {
                    System.err.println(ex.response);
                    try {
                        String body = ex.response.toString();
                        System.err.println(body);
                    } catch (Exception ignored) {
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            //ignore
        }
        return "mmm"; //TODO
    }


}
